<template>
    <div class="pagestyle">
        <list_controller ref="zujianname" :options="state.options" pageName="设备维检" >
            <template v-slot:opraCurdBtnAll>
                <el-button class="btn" type="primary" link @click="addBtn('mul')">
                    <el-icon style="margin-right: 2px;">
                        <svg-icon class-name="search-icon" icon-class="addtotal" />
                    </el-icon>新增
                </el-button>
                <el-button class="btn" type="primary" link @click="deleteBtn('mul')">
                    <el-icon>
                        <DeleteFilled />
                    </el-icon>删除
                </el-button>
                <el-button class="btn" type="primary" link @click="configBtn()">
                    <el-icon>
                        <Edit />
                    </el-icon>区域绑定测点配置
                </el-button>
            </template>
            <template v-slot:opraCurdBtn1="row">
                <span>
                    <el-button type="primary" link size="small" @click="lookBtn(row.row.row)">查看</el-button>
                    <el-button type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
                    <el-button type="primary" link size="small" @click="deleteBtn(row.row.row)">删除</el-button>
                </span>
            </template>
        </list_controller>
        <!-- 新增 -->
        <el-drawer v-model="state.drawerShow" direction="rtl" size="40%" close-on-click-modal :modal="true">
            <template #header="{ close, titleId, titleClass }">
                <h4 class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="dot" /><span>{{state.modalTitle}}</span></h4>
            </template>
            <el-row :gutter="20">
                <el-col :span="24">
                    <p class="fsc" v-if="state.modalTitle != '设备维检详情' && state.modalTitle != '编辑设备维检'">
                        <span class="wn marr5">设备名称</span>
                        <el-tree-select clearable :disabled="state.editpontDis" v-model="state.deviceName"
                            ref="treeRef1" :data="state.searchqueryAllNameList" placeholder="请选择" highlight-current
                            :props="{  children: 'children',value: 'code', label: 'name'}" @change="chuangantreeChange1"
                            check-strictly />
                        <span class="wn marr5 marl20">区域名称</span>
                        <el-tree-select v-model="state.formData.areaId" ref="treeRef" :data="state.searchTreeList"
                            node-key="id" clearable :props="{  children: 'childList',value: 'id', label: 'areaName'}"
                            placeholder="请选择" highlight-current @node-click="nodeclick" check-strictly />
                        <el-button class="marl40" type="primary" @click="yinyonClick">查询</el-button>
                        <el-button type="info" @click="cancelyinyonClick">重置</el-button>
                    </p>
                    <vxe-table :loading="loading" height="300" :data="state.maintenanceDtoList" border="inner"
                        @checkbox-change="checkchange">
                        <vxe-column v-if="state.modalTitle != '设备维检详情' && state.modalTitle != '编辑设备维检'" type="checkbox"
                            :width="42"></vxe-column>
                        <vxe-column v-for="(item,index) in state.options1.tableheads" :field="item.field"
                            :title="item.title" :params="{name:item.name}" :width="item.width?item.width:''"
                            :key="index">
                        </vxe-column>
                    </vxe-table>
                </el-col>
                <el-col :span="24" style="margin-top:50px">
                    <el-form ref="formRef1" label-position="top" :model="state.formData" :rules="state.rules">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="维检类型" prop="maintenanceType">
                                    <el-select :disabled="state.modalTitle == '设备维检详情'" clearable filterable v-model="state.formData.maintenanceType"
                                        placeholder="请选择" @change="maintenanceTypeChange">
                                        <el-option v-for="item in state.searchEffectListData" :key="item.id"
                                            :label="item.maintenanceType" :value="item.maintenanceType">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="开始时间~结束时间">
                                    <el-date-picker  v-model="state.formData.time" type="datetimerange"
                                        range-separator="-" start-placeholder="开始" format="YYYY-MM-DD HH:mm:ss"
                                        value-format="YYYY-MM-DD HH:mm:ss" end-placeholder="结束" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-col>
                <el-col :span="18" style="margin-top:10px" v-if="state.modalTitle != '设备维检详情'">
                    <el-button type="success" @click="openTimeConfigClick">维检默认时间配置</el-button>
                </el-col>
                <el-col :span="6" style="margin-top:10px" v-if="state.modalTitle != '设备维检详情'">
                    <el-button type="info" @click="submitFormcancel">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </el-col>
            </el-row>
        </el-drawer>
        <!-- 维检默认时间配置 -->
        <teleport to="body">
            <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="660" :height="auto"
                v-model="state.addModal" resize :mask="true">
                <template #title>
                    <div class="w100 h100 fsc mask_title">维检默认时间配置</div>
                </template>
                <template #default>
                    <div class="form_box">
                        <el-form ref="formRef" :model="state.formDatatime" :rules="state.rulestime"
                            label-position="top">
                            <el-row :gutter="20">
                                <el-col :span="8" v-for="item in state.maintenancetimeList" :key="item.id">
                                    <el-form-item label="">
                                        <el-switch v-model="item.status"
                                            style="--el-switch-on-color: rgba(91, 109, 128, 0.4); --el-switch-off-color: rgba(64, 158, 255, 1)"
                                            :active-text="item.maintenanceType" />
                                        <div class="fse">
                                            <el-input :disabled="item.status" clearable
                                                v-model="item.maintenanceDuration" placeholder="请输入">
                                            </el-input>
                                            <span class="wn">分钟</span>
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                        <div class="form_footer">
                            <el-button @click="canceltime">取消</el-button>
                            <el-button type="primary" @click="submitFormtime">
                                确定
                            </el-button>
                        </div>
                    </div>
                </template>
            </vxe-modal>
        </teleport>
        <!-- 测点配置 -->
        <teleport to="body">
            <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="800" :height="auto"
                v-model="state.addModalpoint" resize :mask="true">
                <template #title>
                    <div class="w100 h100 fsc mask_title">区域测点配置</div>
                </template>
                <template #default>
                    <div class="form_box">
                        <el-form ref="formRef2" :model="state.formDatapoint" :rules="state.rulespoint"
                            label-position="top">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="设备特性筛选">
                                        <el-tree-select clearable v-model="state.conditionpoint" ref="treeRef1"
                                            :data="state.queryFeatureTreeList" placeholder="请选择" highlight-current
                                            :props="{  children: 'children',value: 'code', label: 'name'}"
                                            @change="chuangantreeChange2" check-strictly />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="选择区域">
                                        <el-tree-select v-model="state.areaIdpoint" ref="treeRef"
                                            :data="state.searchTreeList" node-key="id" clearable
                                            :props="{  children: 'childList',value: 'id', label: 'areaName'}"
                                            placeholder="请选择" highlight-current @change="nodeclick1" check-strictly />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="">
                                        <el-button style="margin-top:30px;" type="primary" @click="submitFormpoint">查询
                                        </el-button>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-form-item label="待选测点">
                                        <vxe-table :loading="loading" height="500" class="w100"
                                            :data="state.formDatapoint.noConfiguredPointList" border="inner"
                                            @checkbox-change="checkchange1">
                                            <vxe-column type="checkbox" width="42"></vxe-column>
                                            <vxe-column field="pointId" title="测点号"></vxe-column>
                                            <vxe-column field="pointName" title="设备名称"></vxe-column>
                                            <vxe-column field="placeName" title="安装地点"></vxe-column>
                                        </vxe-table>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="4">
                                    <div class="fdcc h100">
                                        <span class="spanBox1 hover" @click="confirmClick">
                                            <svg-icon class-name="search-icon" icon-class="addblue" />添加
                                        </span>
                                        <span class="spanBox1 spanBox2 hover" @click="cancelClick" style="margin-top:10px;">
                                            <span><svg-icon class-name="search-icon" icon-class="delred" />移除</span></span>
                                    </div>
                                </el-col>
                                <el-col :span="10">
                                    <el-form-item label="已选测点">
                                        <vxe-table :loading="loading" height="500" class="w100"
                                            :data="state.formDatapoint.configuredPointList"
                                            :checkbox-config="checkboxConfig" @checkbox-change="selectChangeEvent"
                                            border="inner">
                                            <vxe-column type="checkbox" width="42">

                                            </vxe-column>
                                            <vxe-column field="pointId" title="测点号"></vxe-column>
                                            <vxe-column field="pointName" title="设备名称"></vxe-column>
                                            <vxe-column field="placeName" title="安装地点"></vxe-column>
                                        </vxe-table>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                        <div class="form_footer">
                            <el-button @click="cancelpoint">取消</el-button>
                            <el-button type="primary" @click="submitFormponit">
                                确定
                            </el-button>
                        </div>
                    </div>
                </template>
            </vxe-modal>
        </teleport>
    </div>
</template>
<script setup>
    import dayjs from 'dayjs'
    import list_controller from "@/components/commonCom/list_controller";
    import {
        computed,
        reactive
    } from "vue";
    import {
        table_headers
    } from '@/components/commonCom/table_headers';
    import axios from "@/utils/request"
    import usePagesStore from '@/store/modules/pages'
    import {
        getsubstationmodel,
        fileupload,
        searchEffectList,
        searchqueryAllName,
        searchareaTree,
        searchqueryFeatureTree
    } from '@/api/config'
    const {
        proxy
    } = getCurrentInstance();
    const store = usePagesStore()

    components: {
        list_controller
    }
    const upload = ref(null)
    let state = reactive({
        options: {
            tableheads: computed(() => table_headers.deviceMaintenance),
            queryList: {
                dropdownUrl: '',
                querys: [],
                queryMap: new Map([
                    ['sensorTypeId', 'safety_pointType'],
                    ['deviceTypeId', 'safety_deviceType'],
                    ['alarmTypeId', 'alarmType']
                ])
            },
            dataUrl: '/device/maintenance/search',
            delUrl: '/device/maintenance/delete',
            addUrl: '/device/maintenance/add',
            descUrl: '/device/maintenance/search',
            editUrl: '/device/maintenance/modify',
        },
        // 表单
        addModal: false,
        modalTitle: '新增分站类型',
        drawerShow: false,
        formRef: null,
        formData: {},
        rules: {
            maintenanceType: [{
                required: true,
                message: '请输入维检类型',
                trigger: 'change'
            }]
        },
        deviceName: undefined,
        editId: undefined,
        stationmodelList: [],
        stationInNumList: [],
        stationOutNumList: [],
        options1: {
            tableheads: computed(() => table_headers.deviceEquipment),
            queryList: {
                autoSearch: true,
                dropdownUrl: '',
                stationCode: '',
                stationTypeId: '',
                querys: [{
                    field: 'stationCode',
                    title: '编号',
                    type: 'input',
                    binddata: ''
                }],
                queryMap: new Map([
                    ['sensorTypeId', 'safety_pointType'],
                    ['deviceTypeId', 'safety_deviceType'],
                    ['alarmTypeId', 'alarmType']
                ])
            },
            dataUrl: '/device/maintenance/getMaintenanceVo'
        },
        maintenancetimeList: [],
        formDatatime: {},
        rulestime: {},
        searchEffectListData: [],
        searchqueryAllNameList: [],
        searchTreeList: [],
        maintenanceDtoList: [],
        // 测点配置
        addModalpoint: false,
        formDatapoint: {},
        rulespoint: {},
        queryFeatureTreeList: [],
        conditionpoint: undefined,
        areaIdpoint: undefined,
        confirmList: [],
        areaPointList: [],
        areaPointList1: []
    })
    // 表格禁用状态
    const checkboxConfig = reactive({
        // checkMethod: ({
        //     row
        // }) => {
        //     return !row.selected
        // },
        visibleMethod ({ row }) {
            return !row.selected
        }
    })

    function selectChangeEvent(e) {
        state.areaPointList1 = e.records
        state.areaPointList = e.records.map(item => {
            return {
                id: item.id
            }
        })
    }
    // 测点配置按钮
    function configBtn() {
        state.addModalpoint = true
        searchqueryFeatureTree().then(res => {
            state.queryFeatureTreeList = res.data
        })
        getsearchareaTreeList()
        getpointData()
    }

    function getpointData() {
        axios.post('/point/pointList', {
            condition: state.formDatapoint.condition,
            areaId: state.formDatapoint.areaId
        }).then(res => {
            state.formDatapoint = res.data
            if (res.data.configuredPointList != null && res.data.configuredPointList
                .length > 0) {
                    res.data.configuredPointList.forEach(item => {
                    item.selected = true
                })
                state.formDatapoint.configuredPointList=res.data.configuredPointList
            }
        })
    }

    function submitFormpoint() {
        getpointData()
        
    }

    function confirmClick() {
        if(state.formDatapoint.configuredPointList == null ){
            state.formDatapoint.configuredPointList=[]
        }
        state.formDatapoint.noConfiguredPointList = state.formDatapoint.noConfiguredPointList.filter(el => !state
            .confirmList.includes(el))
        state.formDatapoint.configuredPointList = state.formDatapoint.configuredPointList.concat(state.confirmList)
    }

    function cancelClick() {
        state.formDatapoint.configuredPointList = state.formDatapoint.configuredPointList.filter(el => !state
            .areaPointList1.includes(el))
        state.formDatapoint.noConfiguredPointList = state.formDatapoint.noConfiguredPointList.concat(state
            .areaPointList1)
    }

    function submitFormponit() {
        axios.post('/point/modifyPointInfo', {
            areaId: state.areaIdpoint,
            areaPointList: state.areaPointList
        }).then(res => {
            proxy.$modal.msgSuccess(res.msg);
            getpointData()
            state.addModalpoint=false
        })
    }
    function cancelpoint(){
        state.addModalpoint=false
    }
    // 查看按钮
    function lookBtn(row) {
        state.drawerShow = true
        state.modalTitle = '设备维检详情'
        axios.post(state.options.descUrl, {
            id: row.id
        }).then(res => {
            if (res.code == 200) {
                state.formData = res.data.list[0]
                state.options1.queryList.stationTypeId = res.data.list[0].id
                state.formData.time = [res.data.list[0].startTime, res.data.list[0].endTime]
                state.maintenanceDtoList = res.data.list
            }
        })
    }
    // 获取父级id
    function findParentArr(targetId, mock) {
        const ids = []

        function getParent(sources) {
            if (Array.isArray(sources)) {
                return sources.find(elm => {
                    let rs = getParent(elm)
                    if (rs) {
                        ids.push(elm.code)
                    }
                    return rs
                })
            }
            if (sources.code === targetId) {
                return true
            }
            if (Array.isArray(sources.children)) {
                return getParent(sources.children)
            }
        }
        getParent(mock)
        ids.reverse()
        return ids
    }

    function chuangantreeChange1(data) {
        let arr = findParentArr(data, state.searchqueryAllNameList)
        state.formData.deviceName = arr.toString().replace(/,/g, '')
    }

    function chuangantreeChange2(data) {
        let arr = findParentArr(data, state.queryFeatureTreeList)
        state.formDatapoint.condition = arr.toString().replace(/,/g, '')
    }

    function nodeclick1(val) {
        state.formDatapoint.areaId = val
    }

    function getMaintenanceVoList(areaId, deviceName) {
        axios.post('/device/maintenance/getMaintenanceVo', {
            areaId: state.formData.areaId,
            deviceName: state.formData.deviceName
        }).then(res => {
            if (res.code == 200) {
                state.maintenanceDtoList = res.data.list
            }
        })
    }

    function checkchange(e) {
        state.formData.maintenanceDtoList = e.records
    }

    function checkchange1(e) {
        let arr = e.records
        state.confirmList = arr
    }

    function yinyonClick() {
        getMaintenanceVoList()
    }

    function cancelyinyonClick() {
        state.formData.areaId = ''
        state.formData.deviceName = ''
        getMaintenanceVoList()
    }
    // 新增按钮
    function addBtn(row) {
        state.modalTitle = '新增维检设备'
        state.drawerShow = true
        state.formData = {}
        state.editId = undefined
        getsearchEffectList()
        getsearchqueryAllNameList()
        getsearchareaTreeList()
        getMaintenanceVoList()
    }
    // 获取设备名称下拉 
    function getsearchqueryAllNameList() {
        searchqueryAllName().then(res => {
            state.searchqueryAllNameList = res.data
        })
    }
    // 获取设备维检下拉
    function getsearchEffectList() {
        searchEffectList().then(res => {
            state.searchEffectListData = res.data
        })
    }
    // 获取区域名称列表
    function getsearchareaTreeList() {
        searchareaTree().then(res => {
            state.searchTreeList = res.data
        })
    }

    function maintenanceTypeChange(val) {
        state.searchEffectListData.forEach(item => {
            if (item.maintenanceType == val) {
                state.formData.time = [dayjs(), dayjs().add(item.maintenanceDuration, 'minute')]
                state.formData.startTime = dayjs(state.formData.time[0]).format('YYYY-MM-DD HH:mm:ss')
                state.formData.endTime = dayjs(state.formData.time[1]).format('YYYY-MM-DD HH:mm:ss')
                console.log(state.formData.time, item.maintenanceDuration, 'state.formData.time');
            }
        })
    }
    // 编辑按钮
    function editBtn(row) {
        state.modalTitle = '编辑设备维检'
        state.drawerShow = true
        getsearchEffectList()
        axios.post(state.options.descUrl, {
            id: row.id
        }).then(res => {
            if (res.code == 200) {
                state.formData = res.data.list[0]
                state.options1.queryList.stationTypeId = res.data.list[0].id
                state.formData.time = [res.data.list[0].startTime, res.data.list[0].endTime]
                state.maintenanceDtoList = res.data.list
            }
        })
    }
    // 删除
    function deleteBtn(row) {
        let ids = []
        if (row != 'mul') {
            ids = [row.id]
        } else {
            if (store.records.length > 0) {
                ids = store.records.map(item => {
                    return item.id
                })
            } else {
                proxy.$modal.msgSuccess('请先勾选所要删除数据!');
            }
        }
        if (ids.length > 0) {
            axios.post(state.options.delUrl, ids).then(res => {
                if (res.code == 200) {
                    proxy.$refs['zujianname'].getData()
                    state.addModal = false
                    proxy.$modal.msgSuccess(res.msg);
                    store.records = []
                }
            })
        }
    }
    // 维检默认时间配置弹框
    function openTimeConfigClick() {
        state.addModal = true
        state.drawerShow = false
        getmaintenancetime()
    }
    // 获取时间配置列表
    function getmaintenancetime() {
        axios.get('/maintenance/time/search').then(res => {
            console.log(res, 'res');
            state.maintenancetimeList = res.data
        })
    }
    // 提交时间按钮
    function submitFormtime() {
        axios.post('/maintenance/time/modify', state.maintenancetimeList).then(res => {
            if (res.code == 200) {
                proxy.$modal.msgSuccess(res.msg);
                state.addModal = false
                state.drawerShow = true
            }
        })
    }
    // 取消
    function submitFormcancel() {
        state.addModal = false
        state.drawerShow = false
    }
    /** 提交按钮 */
    function submitForm() {
        delete state.formData.areaId
        delete state.formData.deviceName
        delete state.formData.time
        proxy.$refs["formRef1"].validate(valid => {
            if (valid) {
                if (state.editId) {
                    state.formData.id = state.editId
                    axios.post(state.options.editUrl, state.formData).then(res => {
                        if (res.code == 200) {
                            proxy.$refs['zujianname'].getData()
                            state.drawerShow = false
                            proxy.$modal.msgSuccess(res.msg);
                        }
                    })
                } else {
                    axios.post(state.options.addUrl, state.formData).then(res => {
                        if (res.code == 200) {
                            proxy.$refs['zujianname'].getData()
                            state.drawerShow = false
                            proxy.$modal.msgSuccess(res.msg);
                        }
                    })
                }
            }
        })
    }

    function canceltime() {
        state.addModal = false
    }

    function getsubstationmodelList() {
        let arr = []
        getsubstationmodel().then(res => {
            state.stationmodelList = res.data
            state.stationmodelList.forEach(item => {
                arr.push({
                    value: item.id,
                    label: item.stationModelName
                })

            })
        })
    }

    function stationModelChange(val) {
        state.stationmodelList.forEach(item => {
            if (item.id == val) {
                state.stationInNumList = item.stationInNumList
                state.formData.stationInNum = item.stationInNumList[0]
                state.stationOutNumList = item.stationOutNumList
                state.formData.stationOutNum = item.stationOutNumList[0]
            }

        })
    }
    // getsubstationmodelList()
</script>
<style lang="scss" scoped>
    .spanBox1 {
        display: inline-block;
        background-image: url('@/assets/images/configbg.png');
        width: 80px;
        height: 35px;
        line-height: 35px;
        text-align: center;
        &.spanBox2{
            background-image: url('@/assets/images/configbg2.png');
        }
    }

    ::v-deep .el-switch__core {
        border: none;
    }

    ::v-deep .el-switch__label,
    ::v-deep .el-switch__label.is-active {
        color: rgba(62, 70, 79, 0.8);
    }

    ::v-deep .el-drawer {
        .querycss {
            .fsc {
                &:nth-child(2) {
                    display: none;
                }
            }
        }

        .table_box {
            .fsc {
                display: none;
            }
        }
    }
</style>